package com.steven.im.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.adapter.ImagePickerAdapter;
import com.steven.im.base.BaseActivity;
import com.steven.im.base.Constant;
import com.steven.im.entity.BaseEntity;
import com.steven.im.imageLoader.MyImageLoader;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.utils.PermissionUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import me.shaohui.bottomdialog.BottomDialog;
import retrofit2.Response;

/**
 * 我要晒单
 */
public class ShoworderActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    @BindView(R.id.et_content)
    EditText etContent;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    private int maxImgCount = 3;               //允许选择图片最大数
    private String orderId = "";
    private String imgUrl = "";//图片路径
    private int imgCount = 0;//图片数量

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_showorder;
    }

    @Override
    public void initView() {
        new TitleBuilder(this).setTitleText("我要晒单")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                }).setRightText("发布")
                .setRightTextColor(R.color.mainBg)
                .setRightTextListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //发布
                        if (ScreenUtil.isFastClick()) {
                            return;
                        }
                        if (checkInfo()) {
                            if (selImageList.isEmpty()) {//只有文字
                                showOrder();
                            } else {//有图片
                                imgCount = 0;
                                for (int i = 0; i < selImageList.size(); i++) {
                                    uploadImage(selImageList.get(i).path);
                                }
                            }

                        }
                    }
                });

        //获取订单
        orderId = getIntent().getStringExtra("orderId");

        //图片选择器
        initImagePicker();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }

    @Override
    public void initData() {

    }


    /**
     * 初始化图片选择器
     */
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new MyImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(3);                          //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case -1:
                showPhotoDialog();
                break;
            default://打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }


    /**
     * 图片变化后的操作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }


    /**
     * 显示选择图片弹窗
     */
    private void showPhotoDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(ShoworderActivity.this,
                                Manifest.permission.CAMERA)) {
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent = new Intent(ShoworderActivity.this, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(ShoworderActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                        Intent intent1 = new Intent(ShoworderActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        bottomDialog.dismiss();
                    }
                });
            }
        }).setLayoutRes(R.layout.layout_image_select)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }


    /**
     * 检查信息
     */
    private boolean checkInfo() {
        if (TextUtils.isEmpty(etContent.getText().toString().trim())) {
            ToastUtil.showShort(this, "请输入评论内容");
            return false;
        }
        return true;
    }

    /**
     * 上传图片
     */
    private void uploadImage(String imgPath) {
        String userid = SPUtils.get(getApplicationContext(), Constant.UserInfo.ID, "").toString();
        final String pathName = "feedback/userid_" + userid + "_" + System.currentTimeMillis() + ".png";//服务器地址
        Log.i("pathName", pathName);

        //构造上传请求
        String backetName = SPUtils.get(getApplicationContext(), Constant.AliOOS.BACKET_NAME, "").toString();
        PutObjectRequest put = new PutObjectRequest(backetName, pathName, imgPath);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        App.getOSS().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                imgCount++;//图片数量计数
//                Log.i("PutObject", "UploadSuccess");
                String domain = SPUtils.get(getApplicationContext(), Constant.AliOOS.DOMAIN, "").toString();
                String picPath = domain + File.separator + pathName;
//                Log.i("图片路径", "路径：" + picPath);
                imgUrl += picPath + ",";
                if (imgCount == selImageList.size()) {
                    showOrder();
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                ToastUtil.showShort(ShoworderActivity.this, "上传图片失败");
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

    }


    /**
     * 晒单
     */
    private void showOrder() {
        String cont = etContent.getText().toString().trim();
        Task.getApiService().showOrder(orderId, cont, imgUrl).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    ToastUtil.showShort(ShoworderActivity.this,
                            response.body().getMessage());
                    if ("0".equals(response.body().getCode())) {
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }


}
